package com.example.dao.impl;

import com.example.dao.IUserDao;
import com.example.entity.User;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;
import java.util.List;

/**
 * Created by 01182800 on 2017/2/24.
 */
@Repository
public class UserDao implements IUserDao {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public List<User> findAll() {
        CriteriaQuery<User> criteria = this.entityManager.getCriteriaBuilder().createQuery(User.class);
        return this.entityManager.createQuery(criteria).getResultList();
    }

    @Override
    public User getById(Integer id) {
        return this.entityManager.find(User.class, id);
    }

    @Override
    public void save(User user) {
        this.entityManager.persist(user);
    }

    @Override
    public void update(User user) {
        this.entityManager.merge(user);
    }

    @Override
    public void delete(Integer id) {
        this.entityManager.remove(this.entityManager.find(User.class, id));
    }
}
